package com.jerry.usbserial.adapter

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.jerry.usbserial.R
import com.jerry.usbserial.util.*
import kotlinx.android.synthetic.main.dlg_menu_edit.view.*
import kotlinx.android.synthetic.main.item_menu_content.view.*

/**
 * Created by dugang on 2020/7/5.
 */
class MenuAdapter(private val mContext: Context) : BaseAdapter() {
    private val mInflater: LayoutInflater by lazy { LayoutInflater.from(mContext) }
    private val mList = mutableListOf<MenuItem>()
    private var mSelectedListener: (() -> Unit)? = null

    override fun getItem(position: Int): MenuItem = mList[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getCount(): Int = mList.size

    fun addMenu() {
        add(MenuItem(0, "", 0, 0))
    }

    fun updateMenu(data: List<MenuItem>) {
        val insertList = mutableListOf<MenuItem>()
        val list = mList.map { it.id }
        data.forEach {
            if (!list.contains(it.id)) insertList.add(it)
        }
        if (insertList.isNotEmpty()) {
            mList.addAll(insertList)
            notifyDataSetChanged()
        }
    }

    private fun add(data: MenuItem) {
        mList.add(data)
        notifyDataSetChanged()
    }

    private fun update(position: Int, data: MenuItem) {
        mList.removeAt(position)
        mList.add(position, data)
        notifyDataSetChanged()
    }

    private fun delete(position: Int) {
        mList.removeAt(position)
        notifyDataSetChanged()
    }

    fun chooseAll(chosen: Boolean) {
        mList.forEach {
            it.update = chosen
        }
        notifyDataSetChanged()
    }

    override fun notifyDataSetChanged() {
        super.notifyDataSetChanged()
        mContext.setSp("menu_data", mList.toJson())
    }

    fun isChosenAll(): Boolean {
        return if (mList.isNotEmpty()) {
            val list = mList.filter { it.update }
            list.size == mList.size
        } else {
            false
        }
    }

    fun setOnSelectedChanged(listener: (() -> Unit)) {
        mSelectedListener = listener
    }

    fun getDataByChecked(): List<MenuItem>? {
        val list = mList.filter { it.update }
        val waitSendList = mutableListOf<Int>()
        val duplicates = mutableListOf<Int>()
        list.map { it.id }.forEach {
            if (waitSendList.contains(it)) {
                duplicates.add(it)
            } else {
                waitSendList.add(it)
            }
        }
        if (duplicates.size > 0) {
            mContext.showToast("序号${duplicates.joinToString(postfix = "\"", prefix = "\"")}存在重复")
            return null
        }
        if (waitSendList.isEmpty()) {
            mContext.showToast("请勾选要更新的菜单")
            return null
        }
        waitSendList.sort()
        val last = waitSendList.last()
        if (last > 39) {
            mContext.showToast("序号\"${last}\"超出范围")
            return null
        }
        return list
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view = convertView ?: mInflater.inflate(R.layout.item_menu_content, parent, false)
        if (view.tag == null) view.tag = ItemViewHolder(view)
        (view.tag as MenuAdapter.ItemViewHolder).initData(position)
        return view
    }

    inner class ItemViewHolder(private val view: View) {
        @SuppressLint("SetTextI18n")
        fun initData(position: Int) {
            view.tv_index.text = getItem(position).id.toString()
            view.tv_name.text = getItem(position).name
            view.tv_name.setOnClickListener {
                showEditDialog(position, getItem(position))
            }
            view.tv_temperature.text = getItem(position).temputer.toString()
            view.tv_duration.text = getItem(position).time.toString()
            view.cb_update.isChecked = getItem(position).update
            view.cb_update.setOnCheckedChangeListener { buttonView, isChecked ->
                if (buttonView.isPressed) {
                    getItem(position).update = isChecked

                    mSelectedListener?.invoke()
                }
            }
        }
    }

    @SuppressLint("InflateParams", "SetTextI18n")
    private fun showEditDialog(position: Int, menuItem: MenuItem) {
        val dialog = Dialog(mContext, R.style.Dialog_Default)
        val view = mInflater.inflate(R.layout.dlg_menu_edit, null)
        dialog.setContentView(view)
        view.dlg_title.text = "编辑"
        view.et_sn.setText(menuItem.id.toString())
        view.et_name.setText(menuItem.name)

        view.et_temputer.filters = arrayOf(InputFilterMinMax(0, 250))
        view.et_temputer.setText(menuItem.temputer.toString())

        view.et_time.filters = arrayOf(InputFilterMinMax(0, 500))
        view.et_time.setText(menuItem.time.toString())

        view.delete.setOnClickListener {
            delete(position)
            dialog.dismiss()
        }
        view.confirm.setOnClickListener {
            val id = view.et_sn.text.toString()
            menuItem.id = (id.ifEmpty { "0" }).toInt()
            menuItem.name = view.et_name.text.toString()
            val temputer = view.et_temputer.text.toString()
            menuItem.temputer = (temputer.ifEmpty { "0" }).toInt()
            val time = view.et_time.text.toString()
            menuItem.time = ((time.ifEmpty { "0" })).toInt()

            update(position, menuItem)
            dialog.dismiss()
        }

        dialog.show()
        dialog.window?.attributes = dialog.window?.attributes?.apply {
            width = mContext.resources.displayMetrics.widthPixels * 9 / 10
        }

    }
}